﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Jamhee.Noctiluca.LightWiki.Markup
{
    abstract class WikiMarkup : IMarkup
    {
        protected Regex _regex;

        protected const string WIKI_ATTACHMENT_FOLDER = "_attachment";

        public WikiMarkup()
        {
            _regex = new Regex(this.MarkupRegEx, RegexOptions.Singleline);
        }

        #region IMarkup Members

        public string ParseMarkup(string text, string docFolder, Uri url, MarkupStack stack)
        {
            // If not match, return original text directly
            if (!this.IsMatch(text))
            {
                return text;
            }

            return ConvertMarkup(text, docFolder, url, stack, _regex);
        }

        public virtual bool IsMatch(string text)
        {
            return _regex.IsMatch(text);
        }

        public abstract bool AddParagraphMarkup { get; }

        #endregion

        protected abstract string ConvertMarkup(string text, string docFolder, Uri url, MarkupStack stack, Regex regex);

        protected abstract string MarkupRegEx { get; }

        protected string CovertURL(string requestURL, Uri currentURL, bool isAttachment)
        {
            if (requestURL.StartsWith("^"))
            {
                if (isAttachment)
                {
                    return currentURL.AbsolutePath.TrimEnd('/') + "/" + WIKI_ATTACHMENT_FOLDER + "/" + requestURL.TrimStart('^');
                }
                else
                {
                    return currentURL.AbsolutePath.TrimEnd('/') + "/" + requestURL.TrimStart('^');
                }
            }

            return requestURL;
        }
    }
}
